﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using EnergyService_CSharp;
using System.Configuration;

namespace ConfigTool
{
    public partial class frmConfig : Form
    {
        CompositionContainer container;

        [ImportMany]
        private IList<IEnergyMonitorPlugin> plugins { get; set; }
        private IEnergyMonitorPlugin selectedPlugin;

        public frmConfig()
        {
            InitializeComponent();
        }

        private void frmConfig_Load(object sender, EventArgs e)
        {
            string exePath = System.IO.Path.Combine(Environment.CurrentDirectory, "EnergyService_CSharp.exe");
            try
            {
                checkBox1.Checked = bool.Parse(ConfigurationManager.OpenExeConfiguration(exePath).AppSettings.Settings["debug_enabled"].Value);
            }
            catch
            {
                // ignore
            }

            plugins = new List<IEnergyMonitorPlugin>();
            LoadPlugins();
            lbPlugins.DoubleClick += new EventHandler(lbPlugins_DoubleClick);
            RefreshList();
        }

        void lbPlugins_DoubleClick(object sender, EventArgs e)
        {
            if (null != selectedPlugin)
            {
                NameValueCollection current = GetCurrentConfig(selectedPlugin.Name);
                NameValueCollection nvc = selectedPlugin.Configure(current);
                if (null != nvc)
                {
                    SaveConfigData(nvc);
                }
            }
        }

        private NameValueCollection GetCurrentConfig(string p)
        {
            NameValueCollection nvc = new NameValueCollection();

            string exePath = System.IO.Path.Combine(Environment.CurrentDirectory, "EnergyService_CSharp.exe");
            Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);

            foreach (KeyValueConfigurationElement kve in config.AppSettings.Settings)
            {
                if (kve.Key.ToLower().StartsWith(p.ToLower()))
                {
                    nvc.Add(kve.Key, kve.Value);
                }
            }

            return nvc;
        }

        private void SaveConfigData(NameValueCollection nvc)
        {
            string exePath = System.IO.Path.Combine(Environment.CurrentDirectory, "EnergyService_CSharp.exe");
            Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
            for (int i = 0; i < nvc.Count; i++)
            {
                string key = nvc.GetKey(i);
                string val = nvc.Get(i);
                if (config.AppSettings.Settings[key] == null)
                {
                    config.AppSettings.Settings.Add(key, val);
                }
                else
                {
                    config.AppSettings.Settings[key].Value = val;
                }
            }
            config.Save(ConfigurationSaveMode.Modified, true);
        }

        private void RefreshList()
        {
            lbPlugins.DataSource = plugins;
            lbPlugins.DisplayMember = "Name";
        }

        private void LoadPlugins()
        {
            try
            {
                DirectoryCatalog currDirCatalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory);
                container = new CompositionContainer(currDirCatalog);
                container.ComposeParts(this);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.ToString());
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            string exePath = System.IO.Path.Combine(Environment.CurrentDirectory, "EnergyService_CSharp.exe");
            Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
            config.AppSettings.Settings["debug_enabled"].Value = checkBox1.Checked.ToString().ToLower();
            config.Save(ConfigurationSaveMode.Modified, true);

            this.Close();
        }

        private void lbPlugins_SelectedIndexChanged(object sender, EventArgs e)
        {
            selectedPlugin = (IEnergyMonitorPlugin)lbPlugins.Items[lbPlugins.SelectedIndex];
            txtDescription.Text = selectedPlugin.Description;
        }

    }
}
